<template>
  <div>
    <el-form :inline="true" :model="searchForm" class="filter-form">
      <el-form-item label="科室">
        <el-select v-model="searchForm.department" placeholder="请选择">
          <el-option v-for="item in departmentList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="医生名称">
        <el-input v-model="searchForm.doctorName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model="searchForm.orderNo" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择">
          <el-option v-for="item in statusList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="就诊时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="—"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="index" label="序号" width="50">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="consultationNo" label="订单号"/>
      <el-table-column prop="deptName" label="科室"/>
      <el-table-column prop="doctorName" label="医生"/>
      <el-table-column prop="username" label="就诊人"/>
      <el-table-column prop="status" label="复诊状态">
        <template slot-scope="scope">
          <span>{{ scope.row.status == '0' ? '初诊' : scope.row.status == '1' ? '复诊' : '不限'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="问诊类型"/>
      <el-table-column prop="startTime" label="问诊时间"/>
      <el-table-column prop="paymentStatus" label="状态">
        <template slot-scope="scope">
          <span>{{ statusMap[scope.row.status] || scope.row.status }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fee" label="金额"/>
      <el-table-column prop="createdAt" label="下单时间"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-link class="action-link" type="primary" @click="onView(scope.row)">查看</el-link>
          <el-link class="action-link" type="danger" @click="onRefund(scope.row)">退费</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px; text-align: left;"
      background
      layout="prev, pager, next, sizes, jumper"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 10, 20, 50]"
    />

    <!-- 查看订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <div class="order-detail-form">
        <el-form label-width="80px" label-position="top">
          <el-form-item label="就诊人">
            <el-input v-model="currentOrder.username" disabled />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="currentOrder.phone" disabled />
          </el-form-item>
          <el-form-item label="身份证">
            <el-input v-model="currentOrder.idCard" disabled />
          </el-form-item>
          <el-form-item label="医生">
            <el-input v-model="currentOrder.doctorName" disabled />
          </el-form-item>
          <el-form-item label="科室">
            <el-input v-model="currentOrder.deptName" disabled />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-input v-model="currentOrder.createdAt" disabled />
          </el-form-item>
          <el-form-item label="问诊类型">
            <el-input v-model="currentOrder.type" disabled />
          </el-form-item>
          <el-form-item label="状态">
            <span>{{ statusMap[currentOrder.paymentStatus] || currentOrder.paymentStatus }}</span>
          </el-form-item>
        </el-form>
        <div class="consult-detail-title">咨询详情</div>
        <div class="consult-detail-box">
          <div class="consult-header">
            <span class="name">{{ currentOrder.username }}</span>
            <span class="age">{{ currentOrder.age }}岁</span>
            <span class="gender">{{ currentOrder.gender }}</span>
            <el-tag size="mini">{{ currentOrder.type }}</el-tag>
            <el-tag size="mini" type="info" style="float:right;">患者</el-tag>
          </div>
          <div class="consult-info">
            <div>患者信息：{{ currentOrder.username }} {{ currentOrder.gender }} {{ currentOrder.age }}岁</div>
            <div>本次问诊：{{ currentOrder.consultContent }}</div>
            <div>患病时间：{{ currentOrder.illTime }}</div>
            <div>用药情况：{{ currentOrder.medicine }}</div>
            <div>既往病史：{{ currentOrder.history }}</div>
            <div>过敏情况：{{ currentOrder.allergy }}</div>
            <div>过往情况：{{ currentOrder.past }}</div>
          </div>
          <div class="consult-images">
            <div v-for="(img, idx) in currentOrder.images" :key="idx" class="img-item">
              <el-image :src="img" fit="cover" style="width:80px;height:80px;" />
            </div>
          </div>
          <div class="consult-tip">线上咨询无法替代面诊，如有紧急情况请前往医院就医</div>
        </div>
        <div class="doctor-reply">
          <el-tag size="mini" type="info">医生</el-tag>
          <el-input
            type="textarea"
            :rows="2"
            v-model="currentOrder.doctorReply"
            disabled
          />
        </div>
        <div class="doctor-reply">
          <el-tag size="mini" type="info">医生</el-tag>
          <el-card class="prescription-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>电子处方</span>
              <el-tag size="mini" type="success" style="float:right;">已通过</el-tag>
            </div>
            <div>
              <div>{{ currentOrder.username }} {{ currentOrder.age }}岁 {{ currentOrder.gender }}</div>
              <div>诊断：{{ currentOrder.diagnosis }}</div>
              <div>建议用药：{{ currentOrder.suggestion }}</div>
              <div>{{ currentOrder.prescriptionDate }}</div>
              <el-link type="primary" :underline="false">查看处方</el-link>
            </div>
          </el-card>
        </div>
        <div class="prescription-tip">
          请保存和遵医嘱按时用药，谨遵医嘱，如有不良反应，请及时停止用药并咨询医生，情况严重请立即前往医院就医
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger">退费</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 页面名称：问诊订单
import axios from "axios";

export default {
  name: 'OrderInquiry',
  data() {
    return {
      searchForm: {
        department: '',
        doctorName: '',
        orderNo: '',
        status: '',
        dateRange: []
      },
      departmentList: ['科室1', '科室2', '科室3'],
      paymentStatus: ['待支付', '待接诊', '进行中', '已取消', '已关闭', '已完成', '已结束'],
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      currentOrder: {
        username: '就诊人1',
        phone: '13723534534',
        idCard: '530123456789012345',
        doctorName: '医生1',
        deptName: '科室1',
        createdAt: '2022-05-04 15:46:30',
        type: '图文问诊',
        paymentStatus: '已完成',
        age: 25,
        gender: '男',
        consultContent: '胃不舒服',
        illTime: '一周内',
        medicine: '服用药物，请自行填写',
        history: 'xxxx，xxxx，xx',
        allergy: '无',
        past: 'xxxxxxx，xxxx',
        images: [
          'https://via.placeholder.com/80',
          'https://via.placeholder.com/80',
          'https://via.placeholder.com/80',
          'https://via.placeholder.com/80',
          'https://via.placeholder.com/80',
          'https://via.placeholder.com/80'
        ],
        doctorReply: '你这个情况xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx。',
        diagnosis: '病症性胃病，xxx，xxxxxxxxxxxx',
        suggestion: '阿莫西林胶囊 OTC，xxxx',
        prescriptionDate: '2022-05-09'
      },
      statusMap: {
        0: '待支付',
        1: '待接诊',
        2: '进行中',
        3: '已取消',
        4: '已关闭',
        5: '已退诊',
        6: '自动结束',
        7: '已完成'
      }
    }
  },
  methods: {
    onSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    onReset() {
      this.searchForm = {
        department: '',
        doctorName: '',
        orderNo: '',
        status: '',
        dateRange: []
      }
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchData()
    },
    fetchData() {
      // 复制参数，避免污染原始表单
      const params = { ...this.searchForm }
      params.pageNum = this.currentPage
      params.pageSize = this.pageSize
      // 如果有日期区间，处理成后端需要的格式
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange

      axios.post('/consultations/page', params)
        .then(res => {
          if (res.data && res.data.code === 200) {
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          } else {
            this.$message.error(res.data.message || '查询失败')
          }
        })
        .catch(() => {
          this.$message.error('网络错误')
        })
    },
    onView(row) {
      axios.get('/consultations/byConsultationsId', {
        params: { consultationId: row.consultationId }
      })
      .then(res => {
        if (res.data && res.data.code === 200) {
          const detail = Array.isArray(res.data.data) ? res.data.data[0] : res.data.data;
          this.currentOrder = { ...this.currentOrder, ...detail };
          this.dialogVisible = true;
        } else {
          this.$message.error(res.data.message || '获取详情失败');
        }
      })
      .catch(() => {
        this.$message.error('网络错误');
      });
    },
    onRefund(row) {
      this.$confirm('确定要对该订单进行退费吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('/consultations/fee', row)
          .then(res => {
            if (res.data && res.data.code === 200) {
              this.$message.success('退费成功');
              this.fetchData();
            } else {
              this.$message.error(res.data.message || '退费失败');
            }
          })
          .catch(() => {
            this.$message.error('网络错误');
          });
      }).catch(() => {});
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.filter-form {
  margin-bottom: 20px;
}
.action-link {
  color: #00a0e9 !important;   /* 蓝色 */
  text-decoration: underline !important; /* 下划线 */
  margin-right: 24px;           /* 两个按钮间距 */
  font-size: 16px;              /* 字体大小可根据实际调整 */
  cursor: pointer;
  padding: 0;
}
.action-link:last-child {
  margin-right: 0;
}
.order-detail-form {
  padding: 10px 30px 0 30px;
}
.consult-detail-title {
  font-weight: bold;
  margin: 20px 0 10px 0;
}
.consult-detail-box {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 16px;
  background: #fafbfc;
}
.consult-header {
  font-weight: bold;
  margin-bottom: 8px;
}
.consult-info > div {
  margin-bottom: 4px;
}
.consult-images {
  display: flex;
  flex-wrap: wrap;
  margin: 10px 0;
}
.img-item {
  margin-right: 8px;
  margin-bottom: 8px;
}
.consult-tip {
  color: #e6a23c;
  font-size: 12px;
  margin-top: 8px;
}
.doctor-reply {
  margin-bottom: 16px;
}
.prescription-card {
  margin-top: 8px;
}
.prescription-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 12px;
}
</style> 